package cc.ufinity.networkdiagnose.widget;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.util.StringUtils.PING_RESULT;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class PingWidgetProxy extends GeneralTestWidget {

    private ScrollView pingSv;
    private LinearLayout pingRsLayout;
    private Activity ctx;
    private Handler handler;
    private Button backBtn;
    private NetworkManager nm;
    private Task task;
    private PingTask pingTask;
    private int taskSize;
    private boolean taskProcessing;
    private int currentTaskNum;

    public PingWidgetProxy(Activity context) {
        super(context);
        inflate(context, R.layout.ping_proxy, this);
        this.ctx = context;
        pingSv = (ScrollView) this.findViewById(R.id.ping_test_proxy_ScrView);
        pingRsLayout = (LinearLayout) this.findViewById(R.id.pint_test_proxy_detail);
        backBtn = (Button) this.findViewById(R.id.ping_test_proxy_btnback);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.PING_SUCCESS:
                    update();
                    break;
                case MessageWhat.PING_FAILED:
                    showMessage(ctx, "PING测试失败，请返回重试！");
                    dismissProgressDialog();
                    break;
                case MessageWhat.DO_NEXT_TEST:
                    showTaskResult();
                    break;
                }
            }
        };
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });
        nm = new NetworkManager();
        nm.setHandler(handler);
        startPing();
    }

    private void showTaskResult() {
        if (task.selNetType == ConnectivityManager.TYPE_WIFI) {
            ApRelevanceTestWidgetProxy ap = new ApRelevanceTestWidgetProxy(ctx);
            ctx.setContentView(ap);
        } else {
            TaskResult fp = new TaskResult(ctx);
            ctx.setContentView(fp);
        }
    }

    private void doNextTest() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                nm.sendMsg(MessageWhat.DO_NEXT_TEST);
            }
        };
        Timer t = new Timer();
        t.schedule(timerTask, TASK_PERFORM_INTERVAL);
        this.showMessage(ctx, "PING测试已完成，10秒后进入下一环节.");
    }

    public void update() {
        this.setDialogProgress(currentTaskNum);
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(nm.getPingResult());
        pingRsLayout.addView(tv);
        setScrollViewDown(pingSv);
        Map<String, String> res = StringUtils.pingResult(nm.getPingResult());
        pingTask.bytes = res.get(PING_RESULT.PING_RESULT_BYTE_NO);
        pingTask.time = res.get(PING_RESULT.PING_RESULT_TIME);
        pingTask.ttl = res.get(PING_RESULT.PING_RESULT_TTL);
        task.pingTasks.set(currentTaskNum - 1, pingTask);
        taskProcessing = false;
        if (currentTaskNum == taskSize) {
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);
            dismissProgressDialog();
            doNextTest();
        }
    }

    public void startPing() {
        currentTaskNum = 0;
        taskProcessing = false;
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        final List<PingTask> tasks = task.pingTasks;
        taskSize = tasks.size();
        this.showProgressDialog(ctx, "正在进行Ping测试...", taskSize);
        new Thread() {
            public void run() {
                while (currentTaskNum < taskSize) {
                    if (!taskProcessing) {
                        pingTask = tasks.get(currentTaskNum);
                        currentTaskNum++;
                        taskProcessing = true;
                        nm.ping(pingTask.address, task.testCount, 64);
                    }
                }
            }
        }.start();

    }
}
